

function printStatus(myResponse, myRequest, status) {


   
    var resourceKeys = "";
    for (var key in status.resourceMap) {

        resourceKeys += "[" + key + "]";

    }




    var body = '<html>' +
    '<head>' +
    '<meta http-equiv="Content-Type" ' +
    'content="text/html; charset=UTF-8" />' +
    '</head>' +
    '<body>' +
    '<div> ' +
    'isStarted:' + status.isStarted + '<br />' +
    'startedDate:' + status.startedDate.toDateString() + " " +
     status.startedDate.toLocaleTimeString() + '<br />' +
    'port:' + status.port + '<br />' +
    'resourceMap:' + resourceKeys + '<br />' +
    'numOfCurrentRequests:' + status.numOfCurrentRequests + '<br />' +
    'precentageOfStaticRequests:' +
     status.precentageOfStaticRequests.toFixed(2) + '% <br />' +
    'precntageOfSuccesfulRequests:' +
     status.precntageOfSuccesfulRequests.toFixed(2) + '% <br />' +

    '</div>' +
    '</body>' +
    '</html>';


    myResponse.body = body;
    myResponse.end();



}

//returns to the client the resource that he requested
function getResource(response, request, rootFolder, status) {



    var fs = require('fs');
    var path = require('path');


    //because of windows '\\' 
    rootFolder = rootFolder.replace("\\", "/");

    var pathname = request.resource;

    var fullFilePath = path.join(rootFolder, path.normalize("/" + pathname));

    var extname = path.extname(pathname);
    var contentType = 'text/html';
    switch (extname) {
        case '.js':
            contentType = 'text/javascript';
            break;
        case '.css':
            contentType = 'text/css';
            break;
        case '.jpg':
            contentType = 'image/jpg';
            break;
        case '.jepg':
            contentType = 'image/jpeg';
            break;
        case '.png':
            contentType = 'image/png';
            break;
        case '.gif':
            contentType = 'image/gif';
            break;
    }


    path.exists(fullFilePath, function (exists) {



        if (exists) {

            if (extname != ".png" && extname != ".jpg" && extname != ".jepg") {

                fs.stat(fullFilePath, function (err, stats) {
                    if (err) {

                        response.status = (err.errno === 34) ? 404 : 500;
                        response.end();

                    } else if (stats.isDirectory()) {

                        response.status = 404;
                        response.end();

                    } else if (stats.isFile()) {


                        fs.readFile(fullFilePath, "utf-8", function (error, content) {

                            if (error) {

                                response.status = 500;
                                response.end();



                            }
                            else {

                                response.status = 200;
                                response.headers["Content-Type"] = contentType;

                                response.body = content;

                                try {
                                    response.end();

                                    status.addSuccesfulCounter();
                                } catch (erro) {

                                    // console.log("error in image()" + erro);
                                }
                            }
                        });

                    }

                });
            } else {


                fs.stat(fullFilePath, function (err, stats) {

                    if (err) {

                        response.status = 500;
                        response.end();



                    }
                    else {
                        var length = stats.size;

                        var s = fs.createReadStream(fullFilePath);
                        s.on('error', function () {
                            response.status = 500;

                            response.end();


                        });

                        s.on('open', function () {

                            response.status = 200;
                            response.headers["Content-Type"] = contentType;
                            response.headers["Content-Length"] = length;


                            try {
                                response.write(); //first send headers to client
                                s.pipe(response.socket, {end:false});

                                status.addSuccesfulCounter();
                            } catch (erro) {

                              //  console.log("error in image(" + fullFilePath + ")" + erro);
                            }

                        });

                    }
                });




            }

        }
        else {
            response.status = 404;


            response.end();



        }
    });



}



//adds a new JST function into the resourceMap
function getJST(pathname,response, request, rootFolder, status) {



    var fs = require('fs');
    var path = require('path');


    //because of windows '\\' 
    rootFolder = rootFolder.replace("\\", "/");

   
    var fullFilePath = path.join(rootFolder, path.normalize("/" + pathname));

    var extname = path.extname(pathname);


    path.exists(fullFilePath, function (exists) {



        if (exists) {




            fs.stat(fullFilePath, function (err, stats) {

                if (err) {

                    response.status = 500;
                    response.end();



                }
                else {

                    fs.readFile(fullFilePath, "utf-8", function (error, content) {

                        if (error) {
                            //file_counter--;
                        }
                        else {


                            var newContent = "";

                            var stop = false;
                            var startIndex = 0;
                            var stopIndex = content.length;
                            while (!stop) {

                                var openingTag = content.indexOf("<%", startIndex);
                                if (openingTag != -1) {

                                    var lines = content.substring(startIndex, openingTag).split("\r\n");
                                    for (var i = 0; i < lines.length; i++) {
                                        newContent += "response.body+=\"" + escape(lines[i]) + "\";\r\n";
                                    }

                                    var closingTag = content.indexOf("%>", openingTag);

                                    lines = content.substring(openingTag + 2, closingTag).split("\r\n");
                                    for (var i = 0; i < lines.length; i++) {
                                        newContent += lines[i] + "\r\n";
                                    }


                                    startIndex = closingTag + 2;


                                } else {

                                    var endlines = content.substring(startIndex).split("\r\n");
                                    for (var i = 0; i < endlines.length; i++) {
                                        newContent += "response.body+=\"" + escape(endlines[i]) + "\";\r\n";
                                    }
                                    
                                 

                                    stop = true;
                                }

                            }



                            newContent += "response.body = unescape(response.body);";
                            newContent += "response.end();";
                           // console.log("newContent_4=" + newContent);

                            var funcy = new Function("request", "response", newContent);

                            var str = fullFilePath.split(":");
                            var str2 = str[0].split(".jst");
                            if (str.length > 1) {
                                str2 = str[1].split(".jst");
                            }



                            var funcKey = str2[0];

                            funcKey = funcKey.slice(rootFolder.length);

                            //because of windows '\\' 
                            funcKey = funcKey.replace(/\\/g, "/");

                            status.resourceMap[funcKey + ".jst"] = funcy;


                            //set a 1 second timer in case noone calls end()  
                            response.setTimeOutTimer(response);

                            status.resourceMap[funcKey + ".jst"](request, response);
                            status.addSuccesfulCounter();



                        }


                    });
                }


            });



        }
        else {
            response.status = 404;


            response.end();



        }
    });



}


exports.printStatus = printStatus;
exports.getResource = getResource;
exports.getJST = getJST;
